import React from "react";
import { useState, useEffect, useRef } from 'react';
import { CFormLabel, CFormInput, CButton, CRow, CCol, CFormSelect } from '@coreui/react';
import { useSelector } from 'react-redux'


const Schedule = () => {
  const [forecastName, setForecastName] = useState([]);
  const [forecastID, setForecastID] = useState(1);
  const [scheduleName, setScheduleName] = useState('schedule');
  const [dateStartSchedule, setDateStartSchedule] = useState('2024-01-29');
  const [messages, setMessages] = useState([]);
  const progressBarRef = useRef(null);
  const [progress, setProgress] = useState(0);
  const [listScheduleNames, setListScheduleNames] = useState([]);
  const [selectedScheduleId, setSelectedScheduleId] = useState(null);
  const token = useSelector((state) => state.token);

  const handleForecastChange = (event) => {
    setForecastID(event.target.value)
  };

  const handleScheduleNameChange = (event) => {
    setScheduleName(event.target.value);
  };

  const handleDateStartScheduleChange = (event) => {
      setDateStartSchedule(event.target.value);
  }

  const updateProgress = (value) => {
    setProgress(value);
    if (progressBarRef.current) {
        progressBarRef.current.style.width = `${value}%`;
    }
  };

  const handleScheduleNameFromSelectChange = (event) => {
    const selectedId = event.target.value;
    setSelectedScheduleId(selectedId);
    console.log(`Выбрано расписание с ID: ${selectedId}`);
  };

  const fetchForecastName = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/forecast/forecast_name`,
            {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            }
        );
        const data = await response.json();
        setForecastName(data);
        if (data.length > 0) {
            setForecastID(data[0].id);
        }
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };

    const handlePrepareSchedule = async () => {
        if (!forecastName) {
            alert('Файл прогноза не выбран');
            return;
        }
    
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/tasks/tasks_schedule`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    schedule_name: scheduleName,
                    date_start_schedule: dateStartSchedule,
                    forecast_id: forecastID,
                }),
            });
    
            if (!response.ok) {
                throw new Error(`HTTP error status: ${response.status}`);
            } else {
                console.log("Запрос успешно выполнен");
            }
        } catch (error) {
            console.error("Ошибка при выполнении запроса:", error);
        }
    };

    const fetchSchedules = async () => {
        try {
          const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/schedule_name`,
            {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            }
          );
          const data = await response.json();
          setListScheduleNames(data);
          setSelectedScheduleId(data[0].id);
        } catch (error) {
          console.error("Ошибка при получении расписаний:", error);
        }
      };


  useEffect(() => {
    fetchForecastName();
    fetchSchedules();
    const intervalId = setInterval(async () => {
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/tasks/tasks?task_type=schedule`,
                {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                }
            );
            if (response.ok) {
                const data = await response.json();
                setMessages(data);
                if (data.progress!== undefined) {
                    setProgress(data.progress);
                }
            }
        } catch (error) {
            console.error("Ошибка при выполнении запроса:", error);
        }
    }, 1000);

    return () => clearInterval(intervalId);
    }, []);
    
    return (
        <>
            <h1>Сформировать расписание</h1>
            <br></br>
            <CRow>
                <CCol xs={2}>
                <CFormLabel>Файл прогноза</CFormLabel>
                </CCol>
                <CCol xs={4}>
                <CFormSelect 
                    aria-label="Выберите файл прогноза"
                    options={forecastName.map(item => ({
                    label: item.filename,
                    value: item.id.toString(),
                    }))}
                    onChange={handleForecastChange}
                />
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Название расписания</CFormLabel>
                </CCol>
                <CCol xs={4}>
                    <CFormInput
                        type="text"
                        placeholder="Название расписания"
                        aria-label="sm input example"
                        onChange={handleScheduleNameChange}
                    />
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Начало расписания</CFormLabel>
                </CCol>
                <CCol xs={4}>
                    <CFormInput
                        type="text"
                        placeholder="дата начала расписания 2024-01-29"
                        aria-label="sm input example"
                        onChange={handleDateStartScheduleChange}
                    />
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CButton
                        color="light"
                        variant="outline"
                        onClick={handlePrepareSchedule}
                        >
                        Сформировать
                    </CButton>
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Прогресс</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <div ref={progressBarRef} style={{ width: '100%', backgroundColor: 'lightgray' }}>
                        <div style={{ width: `${progress}%`, height: '20px', backgroundColor: 'grey' }}></div>
                    </div>
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Результат последней задачи</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    {messages?.msg?.map((message, index) => (
                        <div key={index}>{message}</div>
                    ))}
                    {messages?.error && <div style={{color: 'red'}}>{messages.error}</div>}
                </CCol>
            </CRow>
            <br></br>
        </>
    )
}

export default Schedule